import React from "react";
import ReactDOM from "react-dom";
import "./charts.css";
import img1 from './images/001.jpg';
import img2 from './images/006.jpg';
import img3 from './images/003.jpg';
import img4 from './images/004.jpg';
import img5 from './images/005.jpg';
import img6 from './images/007.jpg';
const images = [img1, img2, img3, img4, img5, img6];
//每个小方块组件 点击显示棋子
function Square(props) {
  return (
    <button className="square" onClick={props.onClick}>
      {props.value}
    </button>
  );
}
//大方块组件
class Board extends React.Component {
  renderSquare(i) {
    return (
      <Square
      className="square"
        value={this.props.squares[i]}
        onClick={() => this.props.onClick(i)}
      />
    );
  }

  render() {
    return (
      <div>
        <div className="board-row">
          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}
        </div>
        <div className="board-row">
          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}
        </div>
        <div className="board-row">
          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}
        </div>
      </div>
    );
  }
}

//整个游戏组件
class Charts extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      //初始化历史记录 棋盘上都是空的
      history: [
        {
          squares: Array(9).fill(null),
        },
      ],
      stepNumber: 0, //游戏最开始步数为0
      xIsNext: true, //判断下一个落子是O还是X

      grid: this.createGrid(),
      selected: [],
      score: 0,
    };
  };

  // 创建游戏网格
  createGrid() {
    const rows = 8;
    const cols = 8;

    const pairedImages = [];
    for (let i = 0; i < rows * cols / 2; i++) {
      const image = images[Math.floor(Math.random() * images.length)];
      pairedImages.push(image, image);
    }

    const shuffledImages = pairedImages.sort(() => Math.random() - 0.5);

    const grid = [];
    for (let i = 0; i < rows; i++) {
      const row = [];
      for (let j = 0; j < cols; j++) {
        row.push(shuffledImages[i * cols + j]);
      }
      grid.push(row);
    }

    return grid;
  }
  // 处理点击方块事件
  handleClick2(row, col) {
    if (this.state.selected.length < 2) {
      this.setState(prevState => ({
        selected: [...prevState.selected, [row, col]],
      }));
    }
  }
  componentDidUpdate() {
    const { selected, grid } = this.state;
    if (selected.length === 2) {
      const [row1, col1] = selected[0];
      const [row2, col2] = selected[1];
      if (grid[row1][col1] === grid[row2][col2]) {
        this.setState((prevState) => {
          const newGrid = [...prevState.grid];
          newGrid[row1][col1] = null;
          newGrid[row2][col2] = null;
          return { grid: newGrid, score: prevState.score + 10 };
        });
      }
      this.setState({ selected: [] });
    }
  }
  endGame() {
    alert(`游戏结束，得分：${this.state.score}`);
    this.setState({ grid: this.createGrid(), score: 0 });
  }

  handleClick(i) {
    const history = this.state.history.slice(0, this.state.stepNumber + 1);
    //使当前落子始终是最新落子
    const current = history[history.length - 1];
    const squares = current.squares.slice();
    //当有玩家胜出时，或者某个 Square 已经被填充时该函数不做任何处理直接返回
    if (calculateWinner(squares) || squares[i]) {
      return;
    }

    squares[i] = this.state.xIsNext ? "🐱" : "🐕";
    this.setState({
      //将新的落子情况加到历史记录数组中
      history: history.concat([
        {
          squares: squares,
        },
      ]),
      stepNumber: history.length,
      xIsNext: !this.state.xIsNext,
    });
  }
  //跳转
  jumpTo(step) {
    this.setState({
      stepNumber: step,
      xIsNext: step % 2 === 0,
    });
  }

  render() {
    const history = this.state.history;
    const current = history[this.state.stepNumber];
    const winner = calculateWinner(current.squares);
    //map() 方法返回一个新数组，数组中的元素为原始数组元素调用函数处理后的值
    const moves = history.map((step, move) => {
    //   这里的move是索引值
      const desc = move ? "回到第" + move+"步" : "重新开局";
      return (
        <li className="bmove" key={move}>
          <button className="move" onClick={() => this.jumpTo(move)}>{desc}</button>
        </li>
      );
    });

    let status;
    if (winner) {
      status = "胜者是 " + winner+"教！";
    } else {
      status = "下一位: " + (this.state.xIsNext ? "🐱": "🐕");
    }

    const { grid, selected, score } = this.state;
    const gridRender = grid.map((row, rowIndex) => {
      return row.map((cell, colIndex) => {
        const isSelected = selected.some(([row, col]) => row === rowIndex && col === colIndex);
        return (
          <div
            key={`${rowIndex}-${colIndex}`}
            className={`${cell} ${isSelected ? 'selected' : ''}`}
            onClick={() => this.handleClick2(rowIndex, colIndex)}
            style={{
              backgroundImage: `url(${cell})`,
              width: '50px',
              height: '50px',
              backgroundSize: 'contain',
            }}
          />
        );
      });
    });


    return (
        <div>
            <h1 style={{textAlign:'center',color:'#9A5F31',fontSize:20,fontWeight:'bolder',marginTop:70}}>猫猫教VS狗狗教</h1>
            <div className="game">
                <div className="game-board">
                <Board
                    className="board"
                    squares={current.squares}
                    onClick={(i) => this.handleClick(i)}
                />
                </div>
                <div className="game-info">
                <div style={{marginLeft:20}}>{status}</div>
                <ol >{moves}</ol>
                </div>
                            <img src={require('./images/介绍1.jpg') } className="game-img1" />
            </div>
            <div style={{width:'80%',height:1,border:'1px solid black',marginLeft:100,marginTop:80}}></div>
            
            {/* 消除 */}
            <div>
                <div>
                    
                </div>
            </div>
            <div className="App">
                <h1 style={{color:'#9A5F31',fontSize:20,fontWeight:'bolder'}}>消消乐小游戏</h1>

                <p>得分：{this.state.score}</p>

                <button onClick={() => this.endGame()} className="move">结束游戏</button>
                <div className="grid">{gridRender}</div>
                
  <img src={require('./images/介绍2.jpg') } className="game-img2" />
            </div>
            <div style={{height:30,width:'100%'}}></div>
        </div>
      
    );
  }
}

// ========================================

// ReactDOM.render(<Game />, document.getElementById("root"));

//判断Winner
function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return squares[a];
        // return ('平局！')
    }
  }
  return null;
}
export default Charts;